
<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <!-- 添加 -->
      <template #header>
        <el-button type="primary" size="default" :icon="Plus" @click="addTrademark">添加</el-button>
      </template>
      <!-- card body -->
      <el-table :data="tabelData" border stripe>
        <el-table-column label="序号" align="center" type="index" width="80" />
        <el-table-column prop="tmName" label="品牌名称"></el-table-column>
        <el-table-column prop="logoUrl" label="品牌LOGO">
          <!-- 作用域插槽  内部接受一个数据row template自定义一个结构 决定要放什么标签 -->
          <template #default="{ row }">
            <!-- <img height="60" :src="row.logoUrl" alt="" /> -->
            <el-image :src="row.logoUrl" fit="fill" :lazy="true" style="height:50px"></el-image>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="warning" size="small" :icon="Edit" @click="updateTrademark(row)">修改</el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="DeleteTrademark(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination style="margin-top: 30px" v-model:page-size="limit" v-model:current-page="page" :pager-count="5"
        layout="sizes,prev , pager, next,jumper" :total="total" />
    </el-card>


    <!-- 蒙版 -->
    <el-dialog v-model="dialogFormVisible" :title="newTrademark.id ? '修改品牌' : '添加品牌'">
      <el-form :model="newTrademark" :rules="trademarkRule" ref="ruleFormRef">
        <el-form-item label="名字" prop="tmName" :label-width="formLabelWidth">
          <el-input autocomplete="off" v-model="newTrademark.tmName" />
        </el-form-item>
        <el-form-item label="图片" prop="logoUrl" :label-width="formLabelWidth">
          <el-upload class="avatar-uploader" :action="`${baseUrl}/admin/product/upload`" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="newTrademark.logoUrl" :src="newTrademark.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="updateOrAddTrademark">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>

</template>

<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
  name: 'Trademark',
})
</script>

<script setup lang="ts">
import { ref, toRefs, onMounted, watch, reactive } from "vue";
/* 图标 */
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadProps, FormRules, FormInstance } from 'element-plus'
//请求
import { requestTrademarkList, requestUpdateTrademark, requestAddTrademark, requestDeleteTrademark } from '@/api/trademark'
///类型
import type { reqTrademarkReturnItemType } from '@/api/trademark'

const formLabelWidth = '140px'
//table数据
const tabelData = ref<any>([]);

//页码逻辑
interface pageDateType {
  page: number;
  limit: number;
  total: number;
}
const pageDate = ref<pageDateType>({
  page: 1,
  limit: 3,
  total: 100,
});

const { page, limit, total } = toRefs(pageDate.value);

//页面请求函数
const getTrademarkList = async () => {
  try {
    const result = await requestTrademarkList({
      page: page.value,
      limit: limit.value,
    })
    //把请求回来的值设置给响应数据
    tabelData.value = result.records;
    total.value = result.total;
  } catch (e) {
    ElMessage.error("false")
  }
}
onMounted(() => {
  //初始化请求数据
  getTrademarkList()
})
//监控变化 刷新函数
watch([page, limit], () => {
  /*  */
  getTrademarkList()
})

//4.弹窗逻辑
//控制弹窗显示隐藏的数据
const dialogFormVisible = ref(false)
/* 拿到对应环境的 代理前缀 */
const baseUrl = import.meta.env.VITE_API_URL;

//获取form表单的实例
const ruleFormRef = ref<FormInstance>();

//收集数据
const newTrademark = ref<reqTrademarkReturnItemType>({
  logoUrl: "",
  tmName: "",
  id: 0,
})

//蒙版
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  /*  */
  newTrademark.value.logoUrl = response.data
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  /* 限制图片 */
  // if (rawFile.type !== 'image/jpeg') {
  //   ElMessage.error('Avatar picture must be JPG format!')
  //   return false
  // } else if (rawFile.size / 1024 / 1024 > 2) {
  //   ElMessage.error('Avatar picture size can not exceed 2MB!')
  //   return false
  // }
  return true
}


//添加逻辑
const addTrademark = () => {

  //先清空上一次可能残留的校验信息
  ruleFormRef.value?.clearValidate();

  //打开蒙版
  dialogFormVisible.value = true
  //清除蒙版内容
  newTrademark.value = {
    logoUrl: "",
    tmName: "",
    id: 0,
  }
}
//修改逻辑
const updateTrademark = async (row: reqTrademarkReturnItemType) => {

  //先清空上一次可能残留的校验信息
  ruleFormRef.value?.clearValidate();

  /* id: 14626
    logoUrl: "http://47.93.148.192:8080/group1/M00/06/C8/rBHu8mMOI3yAM0WQAAETRv-b5lY318.jpg"
    tmName: "11" */
  // console.log("row", row);
  //打开蒙版
  dialogFormVisible.value = true
  //获取当前的数据然后进行回填数据
  //拿到当前的数据浅拷贝赋值给表单的数据newTrademark(为了数据不会互相影响)
  newTrademark.value = { ...row };
}

//添加修改提交逻辑
const updateOrAddTrademark = async () => {
  try {
    //关闭蒙版
    dialogFormVisible.value = false;
    //整体校验
    await ruleFormRef.value?.validate();
    try {
      /* 新增数据 无 id 修改数据 有id */
      if (newTrademark.value.id) {
        //修改提交
        await requestUpdateTrademark(newTrademark.value);
        ElMessage.success("修改成功");
      } else {
        //新增提交
        await requestAddTrademark(newTrademark.value);
        ElMessage.success("新增成功");
        page.value = 1;
      }
    } catch (e) {
      ElMessage(newTrademark.value.id ? "修改错误" : "新增错误");
    }
  } catch (e) {
    ElMessage("请填写合法的值");
  }
  //刷新
  getTrademarkList();
};

//删除逻辑
const DeleteTrademark = async (row: reqTrademarkReturnItemType) => {
  ElMessageBox.confirm(
    '你真的要删除码',
    '提示',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'info',
    }
  )
    .then(async () => {
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      try {
        await requestDeleteTrademark(row.id)
        getTrademarkList();
      } catch (e) {
        ElMessage.error("异常");
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '你点错了吧',
      })
    })




}

//自定义表单规则函数
const checkTmNameLength = (rule: any, value: string, callback: any) => {
  /* 
    value是当前需要被检验的值
    callback是回调函数,如果有参数则代表错误信息,如果没有参数则代表放行
  */
  if (value.length < 2 || value.length > 5) {
    callback("长度必须是2-5");
  } else {
    callback();
  }
};


//9.表单校验规则
const trademarkRule = reactive<FormRules>({
  tmName: [
    { required: true, message: "必须填写品牌名称", trigger: "blur" },
    // { min: 2, max: 5, message: "长度必须是2-5", trigger: "blur" },
    { validator: checkTmNameLength, trigger: "blur" },
  ],
  logoUrl: [{ required: true, message: "必须上传图片", trigger: "change" }],
});






</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.box-card {
  width: 480px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
  